HTML转义

模板对上下文传递的字符串进行输出时,会对以下字符自动转义。

小于号< 转换为 <

大于号> 转换为 >

单引号' 转换为 '

双引号" 转换为 "

与符号& 转换为 &

示例

1)打开booktest/views.py文件,创建视图html_escape。

def html_escape(request):
    context={'content':'

hello world

'} return render(request,'booktest/html_escape.html',context)

2)打开booktest/urls.py文件,配置url。

    url(r'^html_escape/$', views.html_escape),

3)在templates/booktest/目录下创建html_escape.html。



    转义


自动转义:{{content}}


4)运行服务器,在浏览器中输入如下网址。

http://127.0.0.1:8000/html_escape/

转义后标记代码不会被直接解释执行,而是被直接呈现,防止客户端通过嵌入js代码攻击网站.

浏览效果如下图:

转义

关闭转义

过滤器escape可以实现对变量的html转义,默认模板就会转义,一般省略。

{{t1|escape}}

过滤器safe:禁用转义,告诉模板这个变量是安全的,可以解释执行。

{{data|safe}}

1)修改templates/booktest/html_escape.html代码如下。



    转义


自动转义:{{content}}

过滤器safe关闭转义:{{content|safe}}

刷新浏览器后效果如下图:

转义

标签autoescape:设置一段代码都禁用转义,接受on、off参数。

{%autoescape off%}
...
{%endautoescape%}

1)修改templates/booktest/html_escape.html代码如下。



    转义


自动转义:{{content}}

过滤器safe关闭转义:{{content|safe}}
标签autoescape关闭转义: {%autoescape off%} {{content}} {%endautoescape%}

刷新浏览器后效果如下图:

转义

字符串字面值

对于在模板中硬编码的html字符串,不会转义。

1)修改templates/booktest/html_escape.html代码如下:



    转义


自动转义:{{content}}

过滤器safe关闭转义:{{content|safe}}
标签autoescape关闭转义: {%autoescape off%} {{content}} {%endautoescape%}
模板硬编码不转义:{{data|default:'hello'}}

2)刷新浏览器后效果如下图:

转义

如果希望出现转义的效果,则需要手动编码转义。

1)修改templates/booktest/html_escape.html代码如下:



    转义


自动转义:{{content}}

过滤器safe关闭转义:{{content|safe}}
标签autoescape关闭转义: {%autoescape off%} {{content}} {%endautoescape%}
模板硬编码不转义:{{data|default:'hello'}}
模板硬编码手动转义:{{data|default:"<b>123</b>"}}

2)刷新浏览器后效果如下图:

转义